package com.sgl.service;


import com.github.qcloudsms.SmsSingleSenderResult;
import com.sgl.dao.SmsLogMapper;
import com.sgl.entity.SmsLog;
import com.sgl.util.CloudSmsUtil;
import com.sgl.util.ReturnData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class SmsLogService {
    @Autowired
    private SmsLogMapper smsLogMapper;

    @Transactional
    public ReturnData sendRegister(SmsLog smsLog) {
        ReturnData rd = new ReturnData();
        SmsSingleSenderResult sendSmsResponse = null;
        try {
            sendSmsResponse = CloudSmsUtil.send(smsLog.getPhone(), smsLog.getParam());
        } catch (Exception e) {
            smsLog.setStatus(2);
            smsLog.setMsg("请求异常");
            e.printStackTrace();
        }
        Date currentTime = new Date();
        smsLog.setUpdateTime(currentTime);
        smsLog.setCreateTime(currentTime);
        if (sendSmsResponse != null) {
            if( "OK".equals(sendSmsResponse.errMsg) ) {
                // 请求成功
                smsLog.setStatus(1);
            } else {
                smsLog.setStatus(2);
            }
        } else {
            smsLog.setMsg("腾讯云接口返回空，请求异常");
        }
        int count = smsLogMapper.insert(smsLog);
        if(count > 0) {
            return rd.okBack("发送成功");
        }
        return rd.failBack("发送失败");
    }

}
